package com.iov.failurelog.controller;

import com.alibaba.fastjson2.JSON;
import com.iov.failurelog.utils.HbaseTemplate;
import com.iov.failurelog.utils.RedisUtil;
import com.iov.failurelog.vo.VehicleMsgEntity;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;

/**
 * @Author:Adminstr
 * @Date:2023/11/23
 * @Description:
 * @Verson:3.6.3
 */

@Component
@RestController
@RequestMapping("/hbase")
public class HbaseController extends BaseController {


    private Connection connection;
    private HTable table;
    HBaseAdmin admin;

    @Resource
    private HbaseTemplate hbaseTemplate;


    /*链接 Hbase*/
    @PostConstruct
    public void init() throws IOException {
        Configuration configuration = HBaseConfiguration.create();
        //设置zookeeper的地址,可以有多个,以逗号分隔
        configuration.set("hbase.zookeeper.quorum", "192.168.222.128");
        //设置zookeeper的端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        configuration.set("hbase.master", "192.168.222.128:16000");
        configuration.set("hbase.zookeeper.znode", "/hbase");
        configuration.set("hbase.client.keyvalue.maxsize", "1572864000");
        // configuration.set("hadoop.home.dir", "");
        //创建hbase的连接，这是一个分布式连接
        connection = ConnectionFactory.createConnection(configuration);
        //获取hbase中的表
        table = (HTable) connection.getTable(TableName.valueOf("vehicleData"));
        //这个admin是管理table时使用的，比如说创建表
        admin = (HBaseAdmin) connection.getAdmin();
        System.out.println("====================================================================================================");
    }

    /*  创建表*/
    @GetMapping("/createTable")
    public void createTable() throws IOException {
        //声明一个表名  创建列祖 create 'student' ,'info'
        //
        TableName tableName = TableName.valueOf("vehicleData");
        //构造一个表的描述
        HTableDescriptor desc = new HTableDescriptor(tableName);
        //创建列族
        HColumnDescriptor family1 = new HColumnDescriptor("info1");
        //添加列族
        desc.addFamily(family1);
        //创建表
        admin.createTable(desc);
        System.out.println("====================================================================================================");
        System.out.println("创建成功");
    }

    /*查询表是否存在*/
    @GetMapping("/checkTable")
    public void checkTable() throws IOException {
        //声明一个表名
        TableName tableName = TableName.valueOf("bigdata", "student");
        boolean tableExists = admin.tableExists(tableName);
        if (tableExists) {
            System.out.println("====================================================================================================");
            System.out.println("表存在");
        } else {
            System.out.println("====================================================================================================");
            System.out.println("表不存在");
        }
    }

    @GetMapping("/select/{tableName}/{value}")
    public void select(@PathVariable("tableName") String tableName,
                       @PathVariable("value") String value) {
        Map<String, Map<String, String>> map = hbaseTemplate.getResultScannerValueFilter(tableName, value);
        Set<Map.Entry<String, Map<String, String>>> entries = map.entrySet();
        for (Map.Entry<String, Map<String, String>> entry : entries) {
            Map<String, String> entryValue = entry.getValue();
            Set<Map.Entry<String, String>> entrySet = entryValue.entrySet();
            for (Map.Entry<String, String> stringStringEntry : entrySet) {
                String key = stringStringEntry.getKey();
                String value1 = stringStringEntry.getValue();
                System.out.println(key + ":" + value1);
            }
        }
    }


    /*添加数据*/
    @GetMapping("/insertUpdate")
    public void insertUpdate( String vehicleData, String rowKey) throws IOException {
        //构造参数是row key，必传
        Put put = new Put(Bytes.toBytes(rowKey));
        //put.add()已经被弃用了
        //这里的参数依次为，行键 列族/列名  对应的值
        // family 行键  qualifier  列祖  values 数据
        put.addColumn(Bytes.toBytes("info1"), Bytes.toBytes("vindata"), Bytes.toBytes(ByteBuffer.wrap(vehicleData.getBytes())));
        table.put(put); // 添加失败
        table.close();
        //table.put(List<Put>); //通过一个List集合，可以添加一个集合
    }

    /*获取数据*/
    @GetMapping("scanData")
    public TableDataInfo scanData() throws IOException {
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        System.out.println("====================================================================================================");
        ArrayList<VehicleMsgEntity> list = new ArrayList<>();
        for (Result result : resultScanner) {
            //读取单条记录
            byte[] vehicleData = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("vindata"));
            String s1 = new String(vehicleData);
//            String[] split = s1.split("VehicleMsgEntity");

            VehicleMsgEntity vehicleMsgEntity = JSON.parseObject(s1, VehicleMsgEntity.class);
            list.add(vehicleMsgEntity);
        }
        return getDataTable(list);
    }

    private void printResult(ResultScanner resultScanner) {
        for (Result result : resultScanner) {
            //读取单条记录
            byte[] vehicleData = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("vindata"));
            String s1 = new String(vehicleData);
            String[] split = s1.split("VehicleMsgEntity");
            for (String s2 : split) {
                System.out.print(s2);
                System.out.println("  ");
            }
        }
    }

    /**
     * HBase查询列表
     * @author songshijia
     * @date 2023/11/28
     * @return java.util.List<com.mqtt.pojo.TemperatureRecording>
     */
    @GetMapping("list")
    public TableDataInfo list(){
        Map<String, Map<String, String>> temperatureRecording = hbaseTemplate.getResultScanner("vehicleData");

        List<VehicleMsgEntity> list = new ArrayList<>();
        Set<String> set = temperatureRecording.keySet();//1001  1002

        set.forEach(keyrow->{
            Map<String, String> stringStringMap = temperatureRecording.get(keyrow);

            VehicleMsgEntity vehicleMsgEntity1 = JSON.parseObject(stringStringMap.toString(), VehicleMsgEntity.class);
            System.out.println(vehicleMsgEntity1);

//            VehicleMsgEntity vehicleMsgEntity = new VehicleMsgEntity();
//            vehicleMsgEntity.setAbsStatus(Integer.valueOf(stringStringMap.get("absStatus")));
//            vehicleMsgEntity.setAccelerationPedal(stringStringMap.get("accelerationPedal"));
//            vehicleMsgEntity.setAvailableBatteryCapacity(stringStringMap.get("availableBatteryCapacity"));
//            vehicleMsgEntity.setBaseData(stringStringMap.get("baseData"));
//            vehicleMsgEntity.setBatteryInsulationStatus(Integer.valueOf(stringStringMap.get("batteryInsulationStatus")));
//            vehicleMsgEntity.setBatteryMsg(stringStringMap.get("batteryMsg"));
//            vehicleMsgEntity.setBatteryStatus(stringStringMap.get("batteryStatus"));
//            vehicleMsgEntity.setBrakePedal(stringStringMap.get("brakePedal"));
//            vehicleMsgEntity.setChargingEnergyStorageStatus(Integer.valueOf(stringStringMap.get("chargingEnergyStorageStatus")));
//            vehicleMsgEntity.setChargingStatus(Integer.valueOf(stringStringMap.get("chargingStatus")));
//            vehicleMsgEntity.setChgStatus(Integer.valueOf(stringStringMap.get("chgStatus")));
//            vehicleMsgEntity.setCurrent(stringStringMap.get("current"));
//            vehicleMsgEntity.setDcdcStatus(Integer.valueOf(stringStringMap.get("dcdcStatus")));
//            vehicleMsgEntity.setDriveMotorStatus(Integer.valueOf(stringStringMap.get("driveMotorStatus")));
//            vehicleMsgEntity.setDrivingRoute(Integer.valueOf(stringStringMap.get("drivingRoute")));
//            vehicleMsgEntity.setEasStatus(Integer.valueOf(stringStringMap.get("easStatus")));
//            vehicleMsgEntity.setEpsStatus(Integer.valueOf(stringStringMap.get("epsStatus")));
//            vehicleMsgEntity.setFuelConsumptionRate(stringStringMap.get("fuelConsumptionRate"));
//            vehicleMsgEntity.setGear(stringStringMap.get("gear"));
//            vehicleMsgEntity.setHeatingStatus(Integer.valueOf(stringStringMap.get("heatingStatus")));
//            vehicleMsgEntity.setLatitude(stringStringMap.get("latitude"));
//            vehicleMsgEntity.setLongitude(stringStringMap.get("longitude"));
//            vehicleMsgEntity.setMaximumDischargePower(stringStringMap.get("maximumDischargePower"));
//            vehicleMsgEntity.setMaximumFeedbackPower(stringStringMap.get("maximumFeedbackPower"));
//            vehicleMsgEntity.setMcuStatus(stringStringMap.get("mcuStatus"));
//            vehicleMsgEntity.setMileage(stringStringMap.get("mileage"));
//            vehicleMsgEntity.setMotorControllerTemperature(stringStringMap.get("motorControllerTemperature"));
//            vehicleMsgEntity.setMotorCurrent(stringStringMap.get("motorCurrent"));
//            vehicleMsgEntity.setMotorSpeed(stringStringMap.get("motorSpeed"));
//            vehicleMsgEntity.setMotorTemperature(stringStringMap.get("motorTemperature"));
//            vehicleMsgEntity.setMotorTorque(stringStringMap.get("motorTorque"));
//            vehicleMsgEntity.setMotorVoltage(stringStringMap.get("motorVoltage"));
//            vehicleMsgEntity.setNettyVehicleMsgLog(stringStringMap.get("nettyVehicleMsgLog"));
//            vehicleMsgEntity.setOperatingStatus(Integer.valueOf(stringStringMap.get("operatingStatus")));
//            vehicleMsgEntity.setPositionStatus(Integer.valueOf(stringStringMap.get("positionStatus")));
//            vehicleMsgEntity.setPtcStatus(Integer.valueOf(stringStringMap.get("ptcStatus")));
//            vehicleMsgEntity.setRemainingBattery(stringStringMap.get("remainingBattery"));
//            vehicleMsgEntity.setResistance(stringStringMap.get("resistance"));
//            vehicleMsgEntity.setSelfCheckCounter(stringStringMap.get("selfCheckCounter"));
//            vehicleMsgEntity.setSingleBatteryMaxTemperature(stringStringMap.get("singleBatteryMaxTemperature"));
//            vehicleMsgEntity.setSingleBatteryMaxVoltage(stringStringMap.get("singleBatteryMaxVoltage"));
//            vehicleMsgEntity.setSingleBatteryMinTemperature(stringStringMap.get("singleBatteryMinTemperature"));
//            vehicleMsgEntity.setSingleBatteryMinVoltage(stringStringMap.get("singleBatteryMinVoltage"));
//            vehicleMsgEntity.setSmartHardwareMsg(stringStringMap.get("smartHardwareMsg"));
//            vehicleMsgEntity.setSocStatus(Integer.valueOf(stringStringMap.get("socStatus")));
//            vehicleMsgEntity.setSpeed(stringStringMap.get("speed"));
//            vehicleMsgEntity.setTotalBatteryCurrent(stringStringMap.get("totalBatteryCurrent"));
//            vehicleMsgEntity.setTotalBatteryVoltage(stringStringMap.get("totalBatteryVoltage"));
//            vehicleMsgEntity.setVehicleMsgLog(stringStringMap.get("vehicleMsgLog"));
//            vehicleMsgEntity.setVehicleStatus(Integer.valueOf(stringStringMap.get("vehicleStatus")));
//            vehicleMsgEntity.setVehicleStatusMsg(stringStringMap.get("vehicleStatusMsg"));
//            vehicleMsgEntity.setVin(stringStringMap.get("vin"));
//            vehicleMsgEntity.setVoltage(stringStringMap.get("voltage"));

            list.add(vehicleMsgEntity1);
        });

        return getDataTable(list);
    }


}
